package com.example.zhongyingkaoshi.controller;


import com.example.zhongyingkaoshi.entity.Result;
import com.example.zhongyingkaoshi.entity.User;
import com.example.zhongyingkaoshi.service.UserService;
import com.example.zhongyingkaoshi.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^[a-zA-Z0]$") String username, String password){
        //查询用户
        //注册
        User u = userService.findByUserName(username);
        if (u == null){
            userService.register(username,password);
            return Result.success();
        }else {
            return Result.error("用户名已存在");
        }

    }

//    @GetMapping("/list")
//    public Result<Page<User>> getUserList(
//            @RequestParam(required = false) String username,
//            @RequestParam(required = false) String email,
//            @RequestParam(defaultValue = "0") int page,
//            @RequestParam(defaultValue = "10") int size) {
//        Page<User> users = userService.findUsers(username, email, new Page(page, size));
//        return Result.success(users);
//    }
    @PostMapping("/login")
    public Result<String> login(String username, String password){
        // 先检查用户名是否为空
        if (username == null || username.isEmpty()) {
            return Result.error("用户名不能为空");
        }
        // 测试加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        User loginUser = userService.findByUserName(username);
        // 检查查询结果是否为空
        if (loginUser == null) {
            return Result.error("用户名或密码错误");
        }
        String userPassword = loginUser.getPassword();

        boolean isMatch = encoder.matches(password, userPassword);

        if (isMatch) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        } else {
            return Result.error("密码错误");
        }
    }

    @GetMapping("/userinfo")
    public Result<User> userinfo(@RequestHeader(name = "Authorization") String token){
        //根据用户名查询用户
        Map<String,Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }
}






